<?php
namespace app\providers\controller;

use help\IpHelp;
use app\resources\model\Nodes;
use app\resources\model\UserFrp;
use app\providers\BaseController;

/**
 * @Apidoc\Title("安装命令")
 * @Apidoc\Group("pulic")
 * @Apidoc\Sort(1)
 */
class ScriptCmds extends BaseController
{
	/**
     * 节点安装指令
	 * @Apidoc\Url("system/node/install")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("reset", type="ing",require=true,default="0", desc="是否重置容器")
	 * @global login false
	 * @return String
     */
	public function nodeInstall(){
        // curl -sSL http://182.92.105.25:8001/system/node/install?reset=1 | sh
        $reset = input('reset',0);
        $ssh = Nodes::getSecretKey();
        $host = request()->header('host');
		$server = env('APP_HOST');
        //
        $cmds = [];
        $cmds[] = <<<EOF
            #!/bin/bash

            # fonts color
            Green="\\033[32m"
            Red="\\033[31m"
            GreenBG="\\033[42;37m"
            RedBG="\\033[41;37m"
            Font="\\033[0m"

            # notification information
            OK="\${Green}[OK]\${Font}"
            Error="\${Red}[错误]\${Font}"

            # 判断系统
            if [ -f "/usr/bin/yum" ] && [ -d "/etc/yum.repos.d" ]; then
                PM="yum"
            elif [ -f "/usr/bin/apt-get" ] && [ -f "/usr/bin/dpkg" ]; then
                PM="apt-get"
            else
                echo -e "\${Error} \${RedBG} 当前系统为 \${ID} \${VERSION_ID} 不在支持的系统列表内，安装中断 \${Font}"
                exit 1
            fi

            if [ "$(uname -m)" != "x86_64" ]; then
                echo -e "\${Error} \${RedBG} 仅支持amd64架构，安装中断 \${Font}"
                exit 1
            fi

            check_system() {
                \${PM} update -y
                \${PM} install -y curl wget socat squashfs-tools
                # 安装脚本依赖
                if [ "\${PM}" = "yum" ]; then
                    yum install -y epel-release
                    echo -e "\${OK} \${GreenBG} 安装脚本依赖 \${Font}"
                fi
            }

            check_frps() {
                if [ ! -e "/usr/frps/frps.ini" ]; then
                    wget https://github.com/fatedier/frp/releases/download/v0.44.0/frp_0.44.0_linux_amd64.tar.gz
                    tar -zxf frp_0.44.0_linux_amd64.tar.gz
                    rm -f frp_0.44.0_linux_amd64.tar.gz
                    mv frp_0.44.0_linux_amd64 /usr/frps
                    chmod +x /usr/frps/frps
                    echo "\${OK} \${GreenBG} frps安装完成 \${Font}"
                fi
            }

            check_docker() {
                docker --version &> /dev/null
                if [ $? -ne 0 ]; then
                    echo "安装docker环境..."
                    curl -sSL https://get.daocloud.io/docker | sh
                    echo -e "\${OK} \${GreenBG} Docker环境安装完成 \${Font}"
                fi
                systemctl start docker
                echo -e "\${OK} \${GreenBG} Docker 启动 \${Font}"
                #
                docker-compose --version &> /dev/null
                if [ $? -ne  0 ]; then
                    echo -e "安装docker-compose..."
                    curl -s -L "https://get.daocloud.io/docker/compose/releases/download/v2.8.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
                    chmod +x /usr/local/bin/docker-compose
                    ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
                    echo "\${OK} \${GreenBG} Docker-compose安装完成 \${Font}"
                    service docker restart
                fi
            }

            remove(){
                container=$(docker ps -a | grep "weifashi/node-websocket" |  awk 'NR=1 {print $1}')
                if [ "\${container}" ]; then
                    docker stop "\${container}"
                    docker rm "\${container}"
                    echo -e "\${OK} \${GreenBG} 删除容器 \${Font}"
                fi
            }

            removes(){
                container=$(docker images | grep "weifashi/node-websocket" | awk 'NR=1 {print $3}')
                if [ "\${container}" ]; then
                    docker rmi "\${container}"
                    docker image prune -a -f
                    echo -e "\${OK} \${GreenBG} 删除镜像 \${Font}"
                fi
            }

            websocket(){
                docker run -it --pid=host --privileged=true -v /node-websocket:/var/www/bash --name="wfs" -d -p 39970:9000 weifashi/node-websocket
                echo -e "\${OK} \${GreenBG} 启动容器 \${Font}"
                container=$(docker ps -a | grep "weifashi/node-websocket" | awk '{print $1}')
                cmd="nohup php think client --hort='ws://$host/ws?action=system&ssh=$ssh'"
                docker exec -i -d "\${container}" /bin/sh -c "\${cmd}"
            }

            install(){
                check_system
                check_frps
                check_docker
                websocket
            }
            EOF;
        $cmds[] = "remove";
        if($reset){
            $cmds[] = "removes";
        }
        $cmds[] = "install";
        $cmds[] = <<<EOF
            cd /
            result="$(curl "{$server}/system/node/install-success?name=$(hostname)&token=$ssh&timestamp=$(date +%s)" -X POST -d "public=\${public}")"
            if [ "\${result}" != "success" ]; then
                echo -e "\${Error} \${RedBG} 节点安装报告失败，返回：\${result} \${Font}"
                exit 1
            fi
            echo -e "\${result}"
            echo -e "\${OK} \${GreenBG} 安装完成 \${Font}"
            EOF;
        return implode("\n\n", $cmds);
	}

    /**
     * 节点安装成功
	 * @Apidoc\Url("system/node/install-success")
     * @Apidoc\Method("post")
	 * @global login false
	 * @return void
     */
	public function nodeInstallSuccess(){
        if( Nodes::decryptSecretKey(input('token')) ){
            $node = Nodes::where('host',IpHelp::getOnlineIp())->find();
            if($node){
                $node->loading = '';
                $node->save();
            }
        }
        return 'success';
    }
	
    /**
     * 获取frpsCmd
	 * @Apidoc\Url("system/node/get-frps")
     * @Apidoc\Method("get")
	 * @global login false
	 * @return void
     */
	public function getFrpsCmd($id=0,$token=''){
        $frp = UserFrp::find($id);
        if(!$frp){
            throw new \think\Exception('无权限！');
        }
        if(!UserFrp::decryptSecretKey($token?:'')){
            throw new \think\Exception('token错误！');
        }
        $parentDir = UserFrp::DIRECTORY;
        $fileName= $frp->fileName();
        $dirAndName = $parentDir.'/'.$fileName;
        $cmd = <<<EOG
            #####新建文件 - 并添加命令
            #!/bin/sh
            
            #创建目录
            if [ ! -d "$parentDir" ];then
                mkdir -p $parentDir
            fi
            
            #创建文件-添加内容
            cd $parentDir 
            cat>$dirAndName<<-EOF
            [common]
            bind_port={$frp->server_port}
            vhost_http_port={$frp->http_port}
            token={$frp->token}
            EOF
            
            #启动进程
            cd ../
            chmod +x $parentDir/$fileName >/dev/null 2>&1 &&
            nohup ./frps -c $parentDir/$fileName >/dev/null 2>&1 &

            // 成功
            echo 'success'
            EOG;
        return $cmd;  
    }

}



